package com.group4.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.group4.order.config.RabbitMQConfig;
import com.group4.order.entity.Order;


import com.group4.order.mapper.OrderMapper;
import com.group4.order.service.CourseService;
import com.group4.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.group4.order.service.UserService;
import com.group4.order.util.OrderUtil;


import com.study.dto.UserDTO;
import com.study.util.ResponseResult;
import com.study.vo.CourseInfoVO;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author cloud
 * @since 2022-03-10
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    //  发送消息到消息队列的模板
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CourseService courseService;

    @Autowired
    private UserService userService;


    /**
     * 监听死信队列有啥子用,
     * 添加订单
     * BeanUtils属性复制可以把DTO转成实体类
     *
     * @param order
     */
    @Override
    public String addOrder(Order order) throws Exception {
        //判断订单是否为空
        if (order == null) {
            throw new Exception("请选择商品提交订单");
        }
        //计算金额,通过课程id查询课程,获取课程的金额
        ResponseResult byId = courseService.getById(order.getCourseId());
        //强转成课程对象
        CourseInfoVO courseInfoVO = (CourseInfoVO) byId.getData();
        //获取数量
        Integer lessonNum = courseInfoVO.getLessonNum();
        //获取价格
        BigDecimal price = courseInfoVO.getPrice();
        //计算总金额multiply表示乘法,这里表示的是价格乘数量
        BigDecimal totalFee = price.multiply(new BigDecimal(lessonNum));
        //根据订单获取会员id,再获取会员的积分
        String memberId = order.getMemberId();
        ResponseResult<UserDTO> user = userService.getUserById(memberId);
        UserDTO userDTO = user.getData();

        //将Bigdecimal转成int类型,然后把积分设置成金额除10
        int total = totalFee.intValue() / 10;
        //将金额加入订单
        order.setTotalFee(totalFee);
        //设置订单课程名称
        order.setCourseTitle(courseInfoVO.getTitle());
        //设置订单中课程封面图片路径
        order.setCourseCover(courseInfoVO.getCover());
        //设置订单老师的名称
        order.setTeacherName(courseInfoVO.getTeacherId());
        //设置订单用户昵称
        order.setNickname(userDTO.getNickName());
        //随机产生订单编号
        order.setOrderNo(OrderUtil.OrderUtils.getOrderCode());
        //订单创建时间
        order.setGmtCreate(new Date());
        order.setStatus(0);
        order.setPayType(1);
        //添加订单
        orderMapper.insert(order);
        //设置课程的销售数量,使用openfeign来调用课程修改的方法来修改购买数量
         courseService.updateBuyCount(courseInfoVO.getId());

        final ObjectMapper objectMapper = new ObjectMapper();
        //订单未支付,存入ttl,60秒后跳到死信队列,然后监听死信队列
        rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_TOPIC_EXCHANGE, "ttl.1", objectMapper.writeValueAsString(order));
        //订单成功,然后支付成功以后再发送一个邮件
        //objectMapper是把对象转换成json格式,//下面的是交换机个路由
        try {
            //发送订单成功消息
            rabbitTemplate.convertAndSend("order_topic_exchange", "add.email.test", objectMapper.writeValueAsString(order));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //最终返回一个订单编号
       return order.getOrderNo();
    }

    /**
     * 根据订单编号查询订单
     *
     * @param id
     * @return
     */
    @Override
    public Order findOrderById(String id) {

        return orderMapper.selectById(id);
    }

    /**
     * 修改订单
     *
     * @param order
     * @param
     */
    @Override
    public void updateOrder(Order order) {
        orderMapper.updateById(order);
    }

    /**
     * 根据订单id判断是否支付成功
     *
     * @param id
     * @return
     */
    @Override
    public Integer findByIdPay(String id) {
        Order order = orderMapper.selectById(id);
        return order.getStatus();
//         if(order.getStatus()==0){
//             //表示订单未支付,重定向到页面支付界面
//         }else{
//             //订单支付成功,跳转到视频播放页面
//
//         }

    }

    /**
     * 根据订单id删除订单
     *
     * @param id
     */
    @Override
    public void deleteById(String id) {

        orderMapper.deleteById(id);
        //取消订单将消息发到交换机,然后邮箱监听交换机
        //rabbitTemplate.convertAndSend("order_topic_exchange","cancel.email.1","订单取消成功");
    }

    /**
     * 查询所有订单
     *
     * @return
     */
    @Override
    public List<Order> getAll() {
        QueryWrapper<Order> queryWrapper = new QueryWrapper();
        return orderMapper.selectList(queryWrapper);
    }


    @Override
    public int updateStatusByNum(String orderNo) {

        final int i = orderMapper.updateStatusByNum(orderNo);
        return i;
    }

    @Override
    public Order getByOrderNo(String orderNo) {
        final Order order = orderMapper.selectOne(new QueryWrapper<Order>().eq("order_no", orderNo));
        return order;
    }


}
